package com.kevin.spring.tx;

import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.RowCallbackHandler;
import org.springframework.jdbc.core.RowMapper;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.List;

/**
 * Created by loli on 2015/6/11.
 */
public class UserDaoImpl2 extends JdbcTemplate implements UserDaoInter{
    @Override
    public User get(int id) {
        String sql = "select * from user where id=" + id;
        User user = null;
        List<User> list = query(sql, new RowMapper<User>() {
            public User  mapRow(ResultSet rs, int rowNum) throws SQLException{
                User user = new User();
                user.setId(rs.getInt("id"));
                user.setName(rs.getString("name"));
                user.setPassword(rs.getString("password"));
                return user;
            }
        });
        return list.get(0);
    }

    @Override
    public void add(User user) {
        String sql = String.format("insert into user(name, password) values('%s', '%s')", user.getName(), user.getPassword());
        update(sql);
    }

    @Override
    public void update(User user) {
        String sql = String.format("update user set name='%s', password='%s' where id='%d'", user.getName(), user.getPassword(), user.getId());
        update(sql);
    }

    @Override
    public void delete(User user) {
        String sql = "delete from user where id=" + user.getId();
        update(sql);
    }
}
